package task

import (
	"context"
	"google.golang.org/protobuf/types/known/timestamppb"
	"gorm.io/gorm"
	"time"
	"wx-dailydoer/pb"
)

const (
	Monday    = 0b0000001
	Tuesday   = 0b0000010
	Wednesday = 0b0000100
	Thursday  = 0b0001000
	Friday    = 0b010000
	Saturday  = 0b100000
	Sunday    = 0b1000000
)

var (
	weekdays    = []int64{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
	weekdaysMap = map[int64]int64{
		Monday:    1,
		Tuesday:   2,
		Wednesday: 3,
		Thursday:  4,
		Friday:    5,
		Saturday:  6,
		Sunday:    7,
	}
)

type OngoingTask struct {
	gorm.Model
	TaskID     int64  `gorm:"column:task_id;"`
	Name       string `gorm:"column:name;type:VARCHAR(255);"`
	Desc       string `gorm:"column:desc;type:VARCHAR(255);"`
	FinishedAt time.Time
	StartedAt  time.Time
	EndedAt    time.Time
}

func (table *OngoingTask) ConvertToDTO() *pb.OngoingTask {
	return &pb.OngoingTask{
		TaskId:     table.TaskID,
		Id:         int64(table.ID),
		Name:       table.Name,
		Desc:       table.Desc,
		StartedAt:  timestamppb.New(table.StartedAt),
		EndedAt:    timestamppb.New(table.EndedAt),
		FinishedAt: timestamppb.New(table.FinishedAt),
	}
}

func (table *OngoingTask) TableName() string {
	return "task"
}

type OngoingTaskDAO struct {
	db *gorm.DB
}

func NewOngoingTaskDAO(db *gorm.DB) *OngoingTaskDAO {
	return &OngoingTaskDAO{
		db: db,
	}
}

func (dao *OngoingTaskDAO) Create(ctx context.Context, task *OngoingTask) error {
	return dao.db.WithContext(ctx).Create(task).Error
}

func (dao *OngoingTaskDAO) Update(ctx context.Context, task *OngoingTask) error {
	return dao.db.WithContext(ctx).Save(task).Error
}

func (dao *OngoingTaskDAO) Delete(ctx context.Context, task *OngoingTask) error {
	return dao.db.WithContext(ctx).Delete(task).Error
}

func (dao *OngoingTaskDAO) GetById(ctx context.Context, id int64) (*OngoingTask, error) {
	var collection OngoingTask
	err := dao.db.WithContext(ctx).First(&collection, id).Error
	if err != nil {
		return nil, err
	}
	return &collection, nil
}

func (dao *OngoingTaskDAO) GetAll(ctx context.Context) ([]*OngoingTask, error) {
	var collections []*OngoingTask
	err := dao.db.WithContext(ctx).Find(&collections).Error
	if err != nil {
		return nil, err
	}
	return collections, nil
}
